<template>
  <component v-bind="attrs" v-model="_show" :is="componentId" :before-close="beforeClose" :title="title ? title : formData?.[idKey] ? '编辑' : '新增'" @closed="handleClosed">
    <el-form ref="formRef" :model="formData" :label-width="labelWidth" v-bind="formProps">
      <jax-form-group v-model="formData" :json="json">
        <template v-for="slotName in Object.keys($slots)" v-slot:[slotName]="item">
          <slot :name="slotName" v-bind="item"></slot>
        </template>
      </jax-form-group>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </component>
</template>

<script setup>
const emits = defineEmits(['update:modelValue', 'update:show', 'submit'])
const props = defineProps({
  modelValue: Object,
  show: Boolean,
  type: { type: String, default: 'drawer' }, // 类型 dialog、drawer
  json: Object,
  title: String,
  formProps: { type: Object, default: () => {} },
  idKey: { type: String, default: 'id' },
  labelWidth: { type: String, default: '80px' },
})

const formRef = ref()

const componentId = computed(() => {
  const components = {
    dialog: 'el-dialog',
    drawer: 'el-drawer',
  }

  return components[props.type] || 'el-dialog'
})

const attrs = computed(() => {
  return props.type == 'dialog'
    ? {
        width: '512px',
      }
    : {
        size: '512px',
      }
})

const formData = computed({
  get: () => props.modelValue,
  set: (val) => emits('update:modelValue', val),
})

const _show = computed({
  get: () => props.show,
  set: (val) => emits('update:show', val),
})

const handleCancel = () => (_show.value = false)

// 保存
function handleSubmit() {
  if (formRef.value) {
    formRef.value.validate(async (valid) => {
      if (valid) {
        emits('submit', false)
      }
    })
  } else {
    emits('submit', false)
  }
}

// 关闭前
function beforeClose(callback) {
  handleCancel()
  callback()
}

// 关闭后清除值以及验证信息
function handleClosed() {
  formRef.value?.resetFields()
}
</script>
